//
//  CaChidTableViewController.m
//  CarTown
//
//  Created by xionghao on 15/8/21.
//  Copyright (c) 2015年 熊浩. All rights reserved.
//

#import "CaChidTableViewController.h"
#import "CarDetailResdmode.h"
#import "SectionModel.h"
#import "CarDetail.h"
#import "CarTableViewController.h"
#import "CarSourceType.h"
#import "PostCarTableViewController.h"
#import "CarbrandModel.h"
#import <UIImageView+WebCache.h>
#import "NumModel.h"
#import <MJExtension.h>
#import "EditCarDetailViewController.h"
#import "Puser.h"
#import "CarChildTableViewCell.h"
#import "PublishQgViewController.h"
#import "UpdateCarTableViewController.h"
#import "addTableViewController.h"
#import "PostWinTableViewController.h"

@interface CaChidTableViewController ()<EditCarDetailViewControllerDelegate>

@property (nonatomic,strong) NSMutableArray *sectionArray;
@property (nonatomic,weak) UIView *header;
@property (nonatomic,weak) UIButton *cancelbtn;
@property (nonatomic,weak) UIImageView *icon;
@property (nonatomic,weak) UILabel *titlelable;
@property (nonatomic,assign) NSInteger num;
@property (nonatomic,strong) Puser *user;
@end

@implementation CaChidTableViewController
+(instancetype)viewcontroller{
    CaChidTableViewController *cachildvc=[XHMianStory instantiateViewControllerWithIdentifier:@"cahidvc"];
    return cachildvc;
}
-(NSMutableArray *)sectionArray{
    if (_sectionArray==nil) {
        _sectionArray=[NSMutableArray array];
    }
    return _sectionArray;
}
-(Puser *)user{
    if (_user==nil) {
        _user=[Puser getUser];
    }
    return _user;
}
-(void)setMode:(CarprogChildmode *)mode{
    _mode=mode;
    [self loadmode];
    self.navigationItem.title=mode.cat_name;
}
-(void)loadmode{
   
    [self.icon sd_setImageWithURL:[NSURL URLWithString:[NSString getImageURLstr:self.car.brand_logo]] placeholderImage:[UIImage imageNamed:@"placehoder"]];
    self.titlelable.text=self.mode.cat_name;
    NSMutableDictionary *params=[NSMutableDictionary dictionary];
    params[@"action"]=@"model";
    params[@"cid"]=_mode.cat_id;
    params[@"type"]=self.type?self.type:@"5";
    NSInteger power=[self.user.power integerValue];
    if (power==1) {
        params[@"user_id"]=self.user.user_id;
    }else if (power==5){
        params[@"com_id"]=self.user.com_id;
    }else if (power==8){
        params[@"parent_id"]=self.user.parent_id;
        params[@"com_id"]=self.user.com_id;
    }
    [PostUitls Post:maketypeurl parameters:params success:^(id response) {
        NSDictionary *dict=response;
        CarDetailResdmode *resdmode=[CarDetailResdmode CardetailWithDict:dict];
        [self addArray:resdmode.data];
        [self.tableView reloadData];
        if (self.detailindexpath) {
            [self.tableView selectRowAtIndexPath:self.detailindexpath animated:YES scrollPosition:UITableViewScrollPositionMiddle];
              NSMutableDictionary *tiaojia=[NSMutableDictionary dictionary];
            [self settiaojan:tiaojia withIndexPath:self.detailindexpath];
            [self updatecount :tiaojia];
        }else{
            if (self.isFormSS) {
                NSIndexPath *first=[NSIndexPath indexPathForRow:0 inSection:0];
                [self.tableView selectRowAtIndexPath:first animated:YES scrollPosition:UITableViewScrollPositionNone];
                [self updatecount :nil];
            }
        }

        
        NSLog(@"%@",resdmode);
        
    } failure:^(NSError *error) {
        NSLog(@"%@",error);
         [self addArray:nil];
    }];
    
   }

- (void)setExtraCellLineHidden: (UITableView *)tableView{
    
    UIView *view =[ [UIView alloc]init];
    
    view.backgroundColor = [UIColor clearColor];
    
    [tableView setTableFooterView:view];
    
    [tableView setTableHeaderView:view];
    
}


-(void)updatecount:(NSMutableDictionary *)tiaojian{
    NSMutableDictionary *params2=[NSMutableDictionary dictionary];
    params2[@"action"]=@"count";
    NSMutableDictionary *conndict=[NSMutableDictionary dictionary];
    conndict[@"brand_name"]=self.car.brand_name;
    conndict[@"cat_name"]=_mode.cat_name;
    if (tiaojian) {
        CarbrandModel *brand=tiaojian[@"brand"];
        CarprogChildmode *child=tiaojian[@"cartory"];
        CarDetail *detail=tiaojian[@"cardetail"];

        if(![tiaojian[SourceType] isEqualToString:@"全部车源"]&&![tiaojian[SourceType] isEqualToString:@"全部平行进口车"]&&tiaojian[SourceType]){
            conndict[SourceType]=tiaojian[SourceType];
        }else if(tiaojian[SourceType]){
            conndict[@"expc"]=@"中规";
        }
        if (detail) {
            conndict[@"mid"]=detail.ID;
        }
    }
    params2[@"cond"]=[NSString DataTOjsonString:conndict];
    [PostUitls Post:sscarurl parameters:params2 success:^(id response) {
        NSDictionary *dict=response;
        NumModel *mode=[NumModel objectWithKeyValues:dict];
        if ([mode.state integerValue]==400) {
            
            if (!self.DotNotice) {
                NSMutableDictionary *userinfo=[NSMutableDictionary dictionary];
                userinfo[@"num"]=mode.num;
                self.num=[mode.num integerValue];
                NSNotification *notice=[[NSNotification alloc]initWithName:NoticeCount object:nil userInfo:userinfo];
                [[NSNotificationCenter defaultCenter] postNotification:notice];
            }
           
             if (tiaojian) {
                 tiaojian[@"num"]=mode.num;
                 if (self.isFormSS) {
                     NSNotification *notification =[NSNotification notificationWithName:NoticeCarDetail object:nil userInfo:tiaojian];
                     //通过通知中心发送通知
                     [[NSNotificationCenter defaultCenter] postNotification:notification];
                 }else{
//                     NSNotification *notification =[NSNotification notificationWithName:NoticeCartory object:nil userInfo:tiaojian];
//                     //通过通知中心发送通知
//                     [[NSNotificationCenter defaultCenter] postNotification:notification];
                     CarTableViewController *vc=[[CarTableViewController alloc]initWithStyle:UITableViewStylePlain];
                     vc.tiaojian=tiaojian;
                     [self.navigationController pushViewController:vc animated:YES];
                 
                 }
             
             }
        }
    } failure:^(NSError *error) {
        
    }];
    

}
-(void)setupHeader:(CGFloat)width{
    UIView *header=[[UIView alloc] initWithFrame:CGRectMake(0, 0, width, 44)];
    UIImageView *icon=[[UIImageView alloc]initWithFrame:CGRectMake(8, 4, 36, 36)];
    icon.image=[UIImage imageNamed:@"list_icon"];
    [header addSubview:icon];
    _icon=icon;
    UILabel *titlelable=[[UILabel alloc]initWithFrame:CGRectMake(52, 4, width-46, 36)];
    
    titlelable.text=@"品牌";
    titlelable.font=[UIFont systemFontOfSize:14];
    [header addSubview:titlelable];
    self.titlelable=titlelable;
    UIButton *cancelbtn=[[UIButton alloc]initWithFrame:CGRectMake(width-38, 12, 20, 20)];
    [cancelbtn setImage:[UIImage imageNamed:@"ico_bright.png"] forState:UIControlStateNormal];
    [header addSubview:cancelbtn];
    self.cancelbtn=cancelbtn;
    self.header=header;
    [self.cancelbtn addTarget:self action:@selector(cancelclick) forControlEvents:UIControlEventTouchUpInside];
    self.tableView.tableHeaderView=header;
}


-(void)addArray:(NSArray *)array{
    [self.sectionArray removeAllObjects];
   
    if (!self.type) {
        SectionModel *mode1=[[SectionModel alloc]init];
        mode1.name=nil;
        mode1.list=@[@"全部车源"];
        SectionModel *mode2=[[SectionModel alloc]init];
        mode2.name=@"平行进口";
        NSArray *typearray=[CarSourceType getCarSourceType];
        NSMutableArray *typemarray=[NSMutableArray array];
        [typemarray addObject:@"全部平行进口车"];
        for (CarSourceType *type in typearray) {
            if ([type.name isEqualToString:@"中规"]) {
                continue;
            }
            [typemarray addObject:type.name];
        }
        
        mode2.list=typemarray;
        SectionModel *mode3=[[SectionModel alloc]init];
        mode3.name=@"中规";
        NSMutableArray *marry=[NSMutableArray array];
        [marry addObjectsFromArray:array];
        [marry insertObject:@"全部中规车" atIndex:0];
        mode3.list=marry;
        
        [self.sectionArray addObject:mode1];
        [self.sectionArray addObject:mode2];
        [self.sectionArray addObject:mode3];
        [self.tableView reloadData];

    }else{
        SectionModel *mode3=[[SectionModel alloc]init];
        mode3.name=self.mode.cat_name;
        mode3.list=array;
        
        [self.sectionArray addObject:mode3];
        
        if ([self.type integerValue]!=5) {
            SectionModel *mode4=[[SectionModel alloc]init];
            mode4.name=@"";
            
            CarDetail *detail=[[CarDetail alloc]init];
            detail.name=@"自定义车型";
            mode4.list=@[detail];
            [self.sectionArray addObject:mode4];
        }
        
    }
}
-(UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
- (void)viewDidLoad {
    [super viewDidLoad];
    
    // Uncomment the following line to preserve selection between presentations.
    // self.clearsSelectionOnViewWillAppear = NO;
    
    // Uncomment the following line to display an Edit button in the navigation bar for this view controller.
    // self.navigationItem.rightBarButtonItem = self.editButtonItem;
        
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
#warning Potentially incomplete method implementation.
    // Return the number of sections.
    return self.sectionArray.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
#warning Incomplete method implementation.
    // Return the number of rows in the section.
    SectionModel *mode=self.sectionArray[section];
    return mode.list.count;
}
- (void)tableView:(UITableView *)tableView willDisplayHeaderView:(UIView *)view forSection:(NSInteger)section
{
    // Background color
    view.tintColor = UIColorWithRGB(242, 242, 242);
    
    // Text Color
    UITableViewHeaderFooterView *header = (UITableViewHeaderFooterView *)view;
    [header.textLabel setTextColor:UIColorWithRGB(138, 138, 138)];
    [header.textLabel setFont:[UIFont systemFontOfSize:14]];
    // Another way to set the background color
    // Note: does not preserve gradient effect of original header
    // header.contentView.backgroundColor = [UIColor blackColor];
}
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (section==0) {
        return 0;
    }
    return 30;
}

#pragma -mark uitbaleview数据源

-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    SectionModel *mode=self.sectionArray[section];
    return mode.name;
}

-(void)cancelclick{
    if ([_delegate respondsToSelector:@selector(CaChidcancelclick)]) {
        [_delegate CaChidcancelclick];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
   
    CarChildTableViewCell *cell=[CarChildTableViewCell cellWithTablview:tableView];
    cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
    cell.titlelable.highlightedTextColor=tintblue;
    cell.pricelable.highlightedTextColor=tintblue;
    
    SectionModel *mode=self.sectionArray[indexPath.section];
    if (self.type) {
        CarDetail *cardetail=mode.list[indexPath.row];
        cell.titlelable.text=cardetail.name;
        if ([cardetail.price integerValue]!=0) {
            NSString *cprice=[NSString removeZero:cardetail.price];
            
            cell.pricelable.text=[NSString stringWithFormat:@"%@万",cprice];
        }else{
            cell.pricelable.text=nil;
        }
        
    }else{
        if (indexPath.section!=2) {
            cell.pricewith.constant=0;
            cell.titlelable.text=mode.list[indexPath.row];
            cell.pricelable.text=nil;
            
        }else{
            cell.pricewith.constant=72;
            if (indexPath.row==0) {
                cell.titlelable.text=mode.list[0];
                cell.pricelable.text=nil;
            }else{
                CarDetail *cardetail=mode.list[indexPath.row];
                cell.titlelable.text=cardetail.name;
                NSString *cprice=[NSString removeZero:cardetail.price];
                cell.pricelable.text=[NSString stringWithFormat:@"%@万",cprice];
            }
        }

    }
       // Configure the cell...
    
    return cell;
}

-(void)eidtViewControllerClick:(CarDetail *)detail{
    NSMutableDictionary *tiaojian=[NSMutableDictionary dictionary];
    [self noticepost:tiaojian withcardetail:detail];
}


-(void)noticepost:(NSMutableDictionary *)tiaojia withcardetail:(CarDetail *)cardetail{
    if (cardetail!=nil) {
         tiaojia[@"cardetail"]=cardetail;
    }
   
    tiaojia[@"brand"]=self.car;
    tiaojia[@"cartory"]=self.mode;
    NSNotification *notification =[NSNotification notificationWithName:NoticePostGetCar object:nil userInfo:tiaojia];
    //通过通知中心发送通知
    [[NSNotificationCenter defaultCenter] postNotification:notification];
    
    for (UIViewController *vc in self.navigationController.viewControllers) {
        if ([vc isKindOfClass:[PostCarTableViewController class]]||[vc isKindOfClass:[PublishQgViewController class]]||[vc isKindOfClass:[UpdateCarTableViewController class]]||[vc isKindOfClass:[addTableViewController class]]||[vc isKindOfClass:[PostWinTableViewController class]]) {
            [self.navigationController popToViewController:vc animated:YES];
        }
    }

}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [XHUserDeflaut setBool:YES forKey:SHOWFIND];
    NSMutableDictionary *tiaojia=[NSMutableDictionary dictionary];
    self.DotNotice=NO;
    if (self.type) {
        SectionModel *mode=self.sectionArray[indexPath.section];
        CarDetail *cardetail=mode.list[indexPath.row];
        if ([self.type integerValue]!=5&&indexPath.section==1) {
            EditCarDetailViewController *vc=[EditCarDetailViewController viewcontroller];
            vc.delegate=self;
            vc.brand=self.car;
            vc.child=self.mode;
            vc.type=self.type;
            [self.navigationController pushViewController:vc animated:YES];
        }else{
          [self noticepost:tiaojia withcardetail:cardetail];
        }
    }else{
    
    [self settiaojan:tiaojia withIndexPath:indexPath];
    
    [self updatecount:tiaojia];
    
    }
    
    
}

-(NSMutableDictionary *)settiaojan:(NSMutableDictionary *)tiaojia withIndexPath:(NSIndexPath *)indexPath{
    tiaojia[@"brand"]=self.car;
    tiaojia[@"cartory"]=self.mode;
    if (self.carindexpath) {
        tiaojia[@"carindexpath"]=self.carindexpath;
    }
    tiaojia[@"detailindexpath"]=indexPath;
    if (indexPath.section==0) {
        
    }
    else  if(indexPath.section==1){
        SectionModel *sctionmode=self.sectionArray[indexPath.section];
        tiaojia[SourceType]=sctionmode.list[indexPath.row];
        
    }else{
        tiaojia[SourceType]=@"中规";
        SectionModel *sctionmode=self.sectionArray[indexPath.section];
        if (indexPath.row==0) {
            
        }else{
            CarDetail *cardetail=sctionmode.list[indexPath.row];
          
            tiaojia[@"cardetail"]=cardetail;
        }
        
    }
    return tiaojia;
}

/*
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the specified item to be editable.
    return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    } else if (editingStyle == UITableViewCellEditingStyleInsert) {
        // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
    }   
}
*/

/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
}
*/

/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    // Return NO if you do not want the item to be re-orderable.
    return YES;
}
*/

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
